<?php

namespace app\db\controller;

use think\Cache;
use think\Config;
use think\Db;
use think\Validate;

/**
 * 数据库相关接口
 * @author MSQ 2021-8-2
 * MSG提示:DB01000-DB01009
 */
class DbDatabase extends Common
{
    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];
    protected $layout = '';

    public function _initialize()
    {
        parent::_initialize();
        //设置过滤方法
        $this->request->filter(['trim']);
    }

    /**
     * 创建数据库
     * @author MSQ 2021-8-2
     */
    public function createDatabase()
    {
        $usercare_id   = $this->auth->getUsercareinfo('id');
        $parent_id     = $_POST['parent_id'];// 父级数据库id，0为总库
        $database_name = $_POST['database_name'];// 数据库名称
        $origin_template_id    = $_POST['origin_template_id'];// 引用的模板id
        $database_introduction = $_POST['database_introduction'];// 数据库简介

        # 验证数据 含验证自定义模板
        $checkRes = model('DbDatabase')->checkDataForcreateDb($parent_id,$origin_template_id,$database_name);
        if ($checkRes['code'] != 1) return $this->error('DB01009:'.$checkRes['msg']);

        # 创建数据库        
        $createRes = model('DbDatabase')->createDatabase($parent_id,$origin_template_id,$database_name,$database_introduction,$usercare_id);
        if ($createRes['code'] != 1) $this->error('DB01001:'.$createRes['msg']);

        $this->success('创建成功',$createRes['data']);
    }
    /**
     * 获取可选择的总库
     * @author MSQ 2021-8-3
     */
    public function getAllSetectParDb()
    {
        $usercare_id = $this->auth->getUsercareinfo('id');
        if (!$usercare_id) $this->error('DB01002:登录信息错误');

        # 获取当前医务所有可切换的总库
        $database_list = model('DbDatabase')->getAllJoinParDb($usercare_id);   

        $this->success('创建成功',$database_list);
    }
    /**
     * 获取总库下可选择的子库
     * @author MSQ 2021-8-3
     */
    public function getSelectDbByParId()
    {
        $usercare_id = $this->auth->getUsercareinfo('id');
        $database_id = $_POST['database_id'];// 总库id
        if (!$usercare_id || !$database_id) $this->error('DB01003:参数错误');

        # 获取对应总库数据库及其（当前医务加入的）子库信息
        $databaseInfo = model('DbDatabase')->getJoinDbListByParId($usercare_id,$database_id);

        if ($databaseInfo === false) $this->error('DB01004:参数错误');
        if (!$databaseInfo) $this->success('DB01005:未找到可用数据库');
        
        $can_view = model('DbUsercareRelation')->getJoinInfoByDbIds($usercare_id,$database_id,'database_id');
        $databaseInfo['can_view'] = $can_view ? true : false;

        foreach ($databaseInfo['childDbInfo'] as $key => $value) {
            $template_id = model('DbTemplate')->getUseingTemplateByDid($value['id'],'id');
            $databaseInfo['childDbInfo'][$key]['template_id'] = $template_id;
            # 目前查出来的都是有权限的
            $databaseInfo['childDbInfo'][$key]['can_view']    = true;
        }
        # 更新医务最后一次点击的数据库总库id
        model('DbUsercare')->upDefaultSeletDbId($usercare_id,$database_id);

        # 权限更新
        model('DbUsercareRelation')->upAllJoinDbAuth($usercare_id);

        $this->success('创建成功',$databaseInfo);
    }
    /**
     * 删除数据库
     * @author MSQ 2021-8-21
     */
    public function deleteDatabase()
    {
        $database_id = $_POST['database_id'];// 总库id

        $databaseInfo = model('DbDatabase')->getDetails($database_id);
        if (!$databaseInfo) $this->success('DB01006:数据库不存在');

        $usercare_id = $this->auth->getUsercareinfo('id');

        if ($usercare_id != $databaseInfo['usercare_id']) $this->success('DB01007:仅创建者可删除');

        if (!$databaseInfo['status']) $this->success('DB01008:数据库已删除');

        Db::startTrans();
        $res = model('DbDatabase')->deleteDatabase($database_id);
        if (!$res) {
            Db::rollback();
            $this->error('DB01008:操作失败');
        }
        Db::commit();
        $this->success('操作成功');
    }
}
